package widget.dialog;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import library.utils.DisplayUtil;
import widget.R;
import widget.list.ListView;
import widget.list.RecyclerView;

/**
 * Created by HKYS on 2016-7-28.
 */
public class PopupMenuDialog {
    private static WeakReference<AlertDialog> reference;

    public static void show(final Context context, String title, int color, LinkedHashMap<String, View.OnClickListener>... menus) {

        if (!(context instanceof Activity)) {
            return;
        }
        AlertDialog dialog = new AlertDialog.Builder(context, R.style.DialogPopupTheme).create();
        reference = new WeakReference<>(dialog);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {

            }
        });

        dialog.show();
        Window window = dialog.getWindow();

        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = context.getResources().getDisplayMetrics().widthPixels;
        window.setContentView(R.layout.dialog_popup_menu);
        window.setGravity(Gravity.BOTTOM);
        window.setAttributes(lp);


        View decor = dialog.getWindow().getDecorView();
        TextView textView = (TextView) decor.findViewById(R.id.dialog_popup_title);
        ListView listView = (ListView) decor.findViewById(R.id.dialog_popup_list);
        listView.setItemDecoration(dp2px(context, 1), Color.parseColor("#FFCCCCCC"));
        listView.setAdapter(new ListMenuAdapter(menus));
        listView.setOnRecyclerViewListener(new RecyclerView.OnRecyclerViewListener() {
            @Override
            public void onItemClick(Object data, int position) {
                super.onItemClick(data, position);
                dismiss();
            }
        });
        textView.setTextSize(18);
        textView.setTextColor(Color.WHITE);
        textView.setBackgroundColor(color);
        textView.setText(title);
    }

    public static AlertDialog getDialog() {
        return reference != null ? reference.get() : null;
    }

    public static void dismiss() {
        AlertDialog dialog = reference != null ? reference.get() : null;
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    public static boolean isShowing() {
        AlertDialog dialog = getDialog();
        if (dialog != null)
            return dialog.isShowing();
        return false;
    }


    private static class KeyValue<K, V> implements Serializable {
        private K key;
        private V value;

        public KeyValue() {
        }

        public KeyValue(K key, V value) {
            this.key = key;
            this.value = value;
        }

        public K getKey() {
            return key;
        }

        public void setKey(K key) {
            this.key = key;
        }

        public V getValue() {
            return value;
        }

        public void setValue(V value) {
            this.value = value;
        }
    }


    public static final class ListMenuAdapter extends ListView.BaseAdapter<MenuItemHolder> {

        private final List<KeyValue<String, View.OnClickListener>> list = new ArrayList<>();

        public ListMenuAdapter(LinkedHashMap<String, View.OnClickListener>... maps) {
            if (maps != null && maps.length > 0)
                for (int i = 0; i < maps.length; i++) {
                    Map<String, View.OnClickListener> map = maps[i];
                    for (Map.Entry<String, View.OnClickListener> entry : map.entrySet()) {
                        KeyValue<String, View.OnClickListener> item = new KeyValue<>();
                        item.setKey(entry.getKey());
                        item.setValue(entry.getValue());
                        list.add(item);
                    }
                    if (i < maps.length - 1) {
                        list.add(new KeyValue());
                    }
                }
        }

        @Override
        public MenuItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            final Context context = parent.getContext();
            final TextView label = new TextView(context);
            final int pad = dp2px(context, 8);
            label.setTextColor(Color.DKGRAY);
            label.setGravity(Gravity.CENTER);
            label.setPadding(pad, pad, pad, pad);

            label.setBackgroundResource(R.drawable.bg_touch_white);
            label.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

            return new MenuItemHolder(label);
        }

        @Override
        public void onBindViewHolder(MenuItemHolder holder, final int position) {
            final Context context = holder.getItem().getContext();
            final KeyValue<String, View.OnClickListener> item = list.get(position);
            final String name = item.getKey();
            final View.OnClickListener listener = item.getValue();
            if (TextUtils.isEmpty(name)) {
                holder.getItem().setHeight(dp2px(context, 8));
                holder.getItem().setBackgroundColor(Color.parseColor("#FFCCCCCC"));
            } else {
                int minHeight = DisplayUtil.getListItemMinHeight();
                holder.getItem().setMinimumHeight(minHeight);

                holder.getItem().setText(name);
                holder.getItem().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (onRecyclerViewListener != null)
                            onRecyclerViewListener.onItemClick(null, position);
                        if (listener != null)
                            listener.onClick(v);
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            return list != null ? list.size() : 0;
        }
    }

    private static final class MenuItemHolder extends ListView.ViewHolder {

        private TextView item;

        public MenuItemHolder(TextView item) {
            super(item);
            this.item = item;
        }

        public TextView getItem() {
            return item;
        }
    }

    public static int dp2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }
}
